<?php
class User_model extends Model {
	function __construct()
	{
		parent::Model();
	}
	
	function checkLoginData($username, $password)
	{
		$password = hash("sha256", $password);
//		echo $password;
		$this -> db -> select('id') -> from('users') -> where('login', $username) -> where('pass', $password);
		$result = $this -> db -> get();
		if($result -> num_rows() == 1) // if user is found
			return $result -> row() -> id;
		else
			return false;
	}
	
	function getUserData($id)
	{
		$this -> db -> select() -> from('users') -> where('id', $id);
		$result = $this -> db -> get();
		if($result -> num_rows() == 0)
		{
			// this means that there is no user with that id!
			// this maybe should be done in controller, if we would think in purest MVC ideology
			// but it's easier this way :)
			
			redirect("login/logout");
		}
		return $result -> row_array();
	}
	
	function getUsers()
	{
		$this -> db -> select("id, firstname, surname, email, level, login") -> from('users') -> order_by('surname', "ASC") -> order_by('firstname', "ASC");
		$result = $this -> db -> get();
		foreach($result -> result_array() as $row)
		{
			$arr[] = $row;
		}
		
		return $arr;
	}
	
	function manageUser($data, $user_id=0)
	{
		if($user_id) // old user, so we are updating
		{
			$this -> db -> where('id', $user_id);
			if(isset($data['pass']))
				$data['pass'] = hash("sha256", $data['pass']);
			$this -> db -> update('users', $data);
		}
		else // new user
		{
			$data['pass'] = hash("sha256", $data['pass']);
			$this -> db -> insert('users', $data);
		}
		
		return true;
	}
	
	function deleteUser($uid)
	{
//		$this -> db -> where('id', $uid);
		$this -> db -> where('id', $uid) -> delete('users'); 
		return true;
	}
	
	
}

